﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using PAS.Helper;

namespace PAS
{
    public partial class SelectOptionForm : Page
    {
        protected override void OnInit(EventArgs e)
        {
            SetOptionItem();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblPeopleName.Text = Request.QueryString[PeopleInfo.DbName] ?? "";
                lblPeopleGroupName.Text = Request.QueryString[PeopleInfo.DbGroupName] ?? "";
                hdnPeopleId.Value = Request.QueryString["Id"] ?? "";
                if (hdnPeopleId.Value.Length == 0 || lblPeopleName.Text.Length == 0)
                {
                    Alert.MessageBox("请先登入");
                    Response.Redirect("Default.aspx");
                }
                else
                    SetData();
            }
        }

        protected void SetData()
        {
            DataConnHelper hlp = new DataConnHelper();
            StringCollection sc = hlp.GetPeopleOptionSelectItemIds(Convert.ToInt32(hdnPeopleId.Value));
            for(int i=1; i<=ItemAmount;i++)
            {
                Control ctl = FindControl("hdnItemId" + i);
                if(ctl != null && ctl is HtmlInputHidden)
                {
                    if(sc.Contains(((HtmlInputHidden)ctl).Value))
                    {
                        ctl = FindControl("chItemName" + i);
                        ((CheckBox)ctl).Checked = true;
                    }
                }
            }
        }

        private int ItemAmount
        {
            get { object obj =  ViewState["ItemAmount"];
                return obj == null ? 0 : Convert.ToInt32(ViewState["ItemAmount"]);
            }
            set { ViewState["ItemAmount"] = value; }
        }

        private void SetOptionItem()
        {
            DataConnHelper hlp = new DataConnHelper();
            DataTable dtOptionInfos = hlp.GetOptionList();
            if(dtOptionInfos!=null && dtOptionInfos.Rows.Count > 0)
            {
                string tempGroupName = "";
                int groupAmount = 0;
                HtmlGenericControl tempDiv=null;
                for(int i=0;i<dtOptionInfos.Rows.Count;i++)
                {
                    string strId = Convert.ToString(dtOptionInfos.Rows[i]["Id"]);
                    string strName = Convert.ToString(dtOptionInfos.Rows[i][OptionInfo.DbName]);
                    string strGroupName = Convert.ToString(dtOptionInfos.Rows[i][OptionInfo.DbGroupName]);
                    if(strGroupName.Length > 0 && strGroupName.CompareTo(tempGroupName) != 0)
                    {
                        groupAmount++;
                        HtmlGenericControl dvGroupName = new HtmlGenericControl();
                        dvGroupName.TagName = "Div";
                        dvGroupName.Attributes["Class"] = groupAmount % 2 == 0 ? "dvOptionGroupNameAl" : "dvOptionGroupName";
                        dvGroupName.InnerHtml = "<p class='SelectGroupName'>"+strGroupName+"</p>";
                        dvGroupName.ID = "dvOptionGroupName" + groupAmount;
                        tempGroupName = strGroupName;
                        tempDiv = dvGroupName;
                        dvOptionList.Controls.Add(dvGroupName);
                    }
                    if(strName.Length>0 && tempDiv != null)
                    {
                        ItemAmount++;
                        CheckBox cb = new CheckBox();
                        cb.Width = 144;
                        HtmlInputHidden hdn = new HtmlInputHidden();
                        hdn.Value = strId;
                        cb.Text = strName.Trim();
                        cb.ID = "chItemName" + ItemAmount;
                        hdn.ID = "hdnItemId" + ItemAmount;
                        tempDiv.Controls.Add(cb);
                        tempDiv.Controls.Add(hdn);
                    }
                }
            }
        }

        private void SaveOptionItem()
        {
            StringCollection scId = new StringCollection();
            for(int i=1;i<=ItemAmount;i++)
            {
                Control  ctl = FindControl("chItemName" + i);
                if(ctl != null && ctl is CheckBox)
                {
                    CheckBox cb = ((CheckBox) ctl);
                    if(cb.Checked)
                    {
                        ctl = FindControl("hdnItemId" + i);
                        if(ctl!=null && ctl is HtmlInputHidden)
                        {
                            HtmlInputHidden hdn = ((HtmlInputHidden) ctl);
                            scId.Add(hdn.Value);
                        }
                    }
                }
            }
            string strMinAmount = System.Configuration.ConfigurationManager.AppSettings["MinItemAmount"];
            string strMaxAmount = System.Configuration.ConfigurationManager.AppSettings["MaxItemAmount"];

            if (scId.Count < Convert.ToInt32(strMinAmount))
            {
                Alert.MessageBox("至少要先"+strMinAmount+"个比赛项目");
            }
            else if (scId.Count > Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxItemAmount"]))
                Alert.MessageBox("最多只能先"+strMaxAmount+"个比赛项目,当前已经先返了"+scId.Count+"个项目");
            else
            {
                OleDbConnection cn = new OleDbConnection(DataConnHelper.ConnectionString);
                cn.Open();
                OleDbTransaction tran = cn.BeginTransaction();
                OleDbCommand comm = new OleDbCommand();
                try
                {
                    comm.Transaction = tran;
                    comm.Connection = cn;
                    comm.CommandType = CommandType.Text;
                    comm.CommandText = "Delete From People_Option Where PeopleId=" + hdnPeopleId.Value;
                    comm.ExecuteNonQuery();
                    foreach(string strItemId in scId)
                    {
                        comm.CommandText = "Insert into People_Option (PeopleId,OptionId,CreateDate) Values ("+hdnPeopleId.Value+","+strItemId+",'"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"') ";
                        comm.ExecuteNonQuery();
                    }
                    tran.Commit();
                    Alert.MessageBox("比赛报名表提交成功");
                }
                catch
                {
                    tran.Rollback();
                    throw;
                }
                finally
                {
                    cn.Close();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SaveOptionItem();
        }
    }
}